#!/bin/bash
# Second Brain Installer.app — the double-clicked executable (Contents/MacOS/installer).
# Runs as the user, no terminal window, no root. Lays down the brain folder, installs the
# tray login-item, and opens the dashboard. All user-facing messages are native dialogs.
set -u

# Resources/ next to this script's Contents/MacOS holds the payload + code.
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RES="$(cd "$HERE/../Resources" && pwd)"
BRAIN_DEFAULT="$HOME/my-second-brain"

dialog() { /usr/bin/osascript -e "display dialog \"$1\" buttons {\"OK\"} default button 1 with title \"Second Brain\" ${2:-}" >/dev/null 2>&1; }
notify() { /usr/bin/osascript -e "display notification \"$1\" with title \"Second Brain\"" >/dev/null 2>&1; }

# --- pick a Python: bundled frozen binary first (no dependency), else system python3 ---
FROZEN="$RES/bin/SecondBrainTray"
PYTHON=""
TRAY_CMD=""
if [ -x "$FROZEN" ]; then
  TRAY_CMD="$FROZEN"
  PYTHON="$FROZEN"   # the frozen bundle also runs first_run via its entrypoints
else
  PYTHON="$(command -v python3 || echo /usr/bin/python3)"
  if [ ! -x "$PYTHON" ]; then
    dialog "Second Brain needs Python 3, which isn't installed. Install it from python.org (or run 'xcode-select --install'), then double-click this installer again." "with icon caution"
    exit 1
  fi
fi

# --- choose location (default ~/my-second-brain; don't clobber an existing brain) ---
BRAIN="$BRAIN_DEFAULT"
if [ -f "$BRAIN/AGENTS.md" ]; then
  notify "You already have a Second Brain — opening it."
else
  mkdir -p "$BRAIN"
  # copy the template payload (everything except the installer's own resources)
  /usr/bin/rsync -a --exclude 'bin' "$RES/template/" "$BRAIN/" 2>/dev/null || cp -R "$RES/template/." "$BRAIN/"
fi

# --- tray deps if using system Python (best effort; frozen path needs none) ---
if [ -z "${FROZEN_USED:-}" ] && [ "$PYTHON" != "$FROZEN" ]; then
  "$PYTHON" -m pip install --user --quiet --upgrade pystray Pillow pyobjc-framework-Cocoa >/dev/null 2>&1 \
    || "$PYTHON" -m pip install --user --break-system-packages --quiet --upgrade pystray Pillow pyobjc-framework-Cocoa >/dev/null 2>&1 \
    || true
  TRAY_CMD="$PYTHON $BRAIN/dashboard/tray.py"
fi

# --- run the shared bootstrap: git init, login item, start tray, open dashboard ---
if [ "$PYTHON" = "$FROZEN" ]; then
  "$FROZEN" --first-run --brain "$BRAIN" --tray-cmd "$FROZEN"
else
  "$PYTHON" "$RES/first_run.py" --brain "$BRAIN" --tray-cmd "$TRAY_CMD"
fi

dialog "Your Second Brain is ready in your home folder:\n\n$BRAIN\n\nNext: open that folder in Claude Code or OpenAI Codex to get started. The tray icon (top menu bar) opens your private dashboard." "with icon note"
exit 0
